package org.leon.org.leon.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.leon.entity.Token;
import org.leon.org.leon.sentinel.UserSentinelBlock;
import org.leon.org.leon.service.LoginTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    private LoginTokenService loginTokenService;

    @Autowired
    public UserController(LoginTokenService loginTokenService) {
        this.loginTokenService = loginTokenService;
    }

    /**
     * 根据 token 查询邮箱地址
     * @return 邮箱地址
     */
    @GetMapping("/info")
    @SentinelResource(value = "userInfo", blockHandlerClass = UserSentinelBlock.class, blockHandler = "infoBlocked")
    public String info(HttpServletRequest request) {
        String token = "";
        Cookie[] cookies = request.getCookies();
        for(Cookie c : cookies) {
            if (c.getName().equals("token")) {
                token = c.getValue();
                break;
            }
        }
        return loginTokenService.checkToken(token);
    }

    /**
     * 登录(查找验证码表中是否是认证成功的邮箱,如果是生成一个 UUID 作为 token 并写入 cookie 即可)
     * @return 成功后重定向到欢迎页面
     */
    @PostMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password")String password, HttpServletResponse response) {
        Optional<String> optional = loginTokenService.checkEmailAndPassword(email, password);
        if (optional.isPresent()) {
            Cookie tokenCookie = new Cookie("token", optional.get());
            tokenCookie.setDomain("localhost");
            tokenCookie.setPath("/");
            response.addCookie(tokenCookie);

            return "successfully";
        }
        return "failed";
    }

    /**
     * 判断邮箱是否已经注册
     * @return true/false
     */
    @GetMapping("/isRegistered/{email}")
    public Boolean checkRegister(@PathVariable String email) {
        Token tokenEntity = loginTokenService.checkEmailExisted(email);
        return tokenEntity != null;
    }

    /**
     * 注册接口
     * @param email 注册邮箱
     * @param password 注册密码
     * @return  true / false
     */
    @PostMapping("/register/{email}/{password}")
    public String register(@PathVariable String email, @PathVariable String password, HttpServletResponse response) {

        String tokenStr = loginTokenService.register(email, password);
        Cookie tokenCookie = new Cookie("token", tokenStr);
        tokenCookie.setPath("/");
        tokenCookie.setDomain("localhost");
        response.addCookie(tokenCookie);

        return "successfully";
    }

}
